<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">主页</a>
        <a><cite>库存管理</cite></a>
        <a><cite>库存预警</cite></a>
    </div>
</div>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            库存预警
        </div>
        <div class="layui-card-body">
            <div class="layui-row" style="margin-bottom: 10px;">
                <form class="layui-form" lay-filter="formSearch">
                    <button type="button" class="layui-btn" id="alert">发送预警短信</button>
                </form>
            </div>
            <!-- 表格 -->
            <table id="alert-table-parseData" lay-filter="alert-table-parseData"></table>
        </div>
    </div>
</div>

<!-- 工具栏模板 -->
<script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="sendSmsSelected">
      <i class="layui-icon layui-icon-notice"></i>发送选中项预警
    </button>
    <button class="layui-btn layui-btn-sm" lay-event="sendSmsAll">
      <i class="layui-icon layui-icon-notice"></i>发送全部预警
    </button>
  </div>
</script>

<script>
    layui.use(['admin', 'table', 'form', 'laydate', 'jquery'], function () {
        var admin = layui.admin
            , table = layui.table
            , form = layui.form
            , baseUrl = layui.setter.baseUrl
            , $ = layui.$

        // 表格渲染        
        form.render(null, 'formSearch')
        var tableIns = table.render({
            elem: '#alert-table-parseData'
            // 请求地址
            , url: baseUrl + 'storealert'
            , toolbar: '#toolbarDemo'
            , title: '库存预警'
            , cellMinWidth: 120
            // 是否开启加载loding
            , loading: true
            // 数据渲染规定
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , { field: 'uuid', title: '仓库编号', width: 110 }
                , { field: 'name', title: '商品名称' }
                , { field: 'storenum', title: '库存数量', templet: function(d){
                    if(d.stockStatus === 'critical') {
                        return '<span style="color:#FF5722;">' + d.storenum + '</span>';
                    } else if(d.stockStatus === 'warning') {
                        return '<span style="color:#FFB800;">' + d.storenum + '</span>';
                    }
                    return d.storenum;
                }
                }
                , { field: 'outnum', title: '待发货数量' }
                , { title: '库存状态', templet: function(d){
                    if(d.stockStatus === 'critical') {
                        return '<span class="layui-badge layui-bg-red">紧急</span>';
                    } else if(d.stockStatus === 'warning') {
                        return '<span class="layui-badge layui-bg-orange">警告</span>';
                    }
                    return '<span class="layui-badge layui-bg-green">正常</span>';
                }
                }
            ]]
            // 开启分页
            , page: true
            , request: {
                pageName: 'page',
                limitName: 'rows'
            }
            , response: {
                // statusName: 'code',
                statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            , parseData: function (res) {
                var rows = res.data.rows || [];
                
                // 添加库存状态标识
                rows.forEach(function(item) {
                    // 判断库存是否紧张（示例：库存小于待发货数量的2倍）
                    if (item.storenum <= item.outnum * 2) {
                        item.stockStatus = 'critical';
                    } else if (item.storenum <= item.outnum * 5) {
                        item.stockStatus = 'warning';
                    } else {
                        item.stockStatus = 'normal';
                    }
                });
                
                return {
                    "code": res.code,
                    "msg": res.message,
                    "count": res.data.total,
                    "data": rows
                };
            }
        });
        // 监听顶部工具栏事件
        table.on('toolbar(alert-table-parseData)', function(obj){
            var checkStatus = table.checkStatus('alert-table-parseData');
            
            switch(obj.event){
                case 'sendSmsSelected':
                    var selectedData = checkStatus.data;
                    if(selectedData.length === 0){
                        layer.msg('请选择需要发送预警的商品', {icon: 0});
                        return;
                    }
                    sendSmsForItems(selectedData);
                    break;
                case 'sendSmsAll':
                    var allData = table.cache['alert-table-parseData'] || [];
                    if(allData.length === 0){
                        layer.msg('没有可用的库存预警数据', {icon: 0});
                        return;
                    }
                    sendSmsForItems(allData);
                    break;
            }
        });

        // 替换现有的按钮点击事件
        $('#alert').click(function () {
            // 获取数据
            var allData = table.cache['alert-table-parseData'] || [];
            if(allData.length === 0){
                layer.msg('没有可用的库存预警数据', {icon: 0});
                return;
            }
            // 调用短信发送函数
            sendSmsForItems(allData);
        });

        // 提取出公共的发送短信逻辑
        function sendSmsForItems(items) {
            // 构建商品名称列表文本
            var productNames = items.map(function(item) {
                return item.name;
            }).join("、");
            
            if(productNames.length > 20) {
                productNames = productNames.substring(0, 20) + "...";
            }
            
            // 弹出手机号输入框
            layer.prompt({
                title: '请输入接收短信的手机号',
                formType: 0,
                value: '', // 可以设置默认值
                success: function(layero){
                    // 添加手机号验证
                    layero.find('input').attr('maxlength', 11).on('input', function(){
                        this.value = this.value.replace(/\D/g, '');
                    });
                }
            }, function(phoneNumber, index){
                // 验证手机号
                if(!/^1[3-9]\d{9}$/.test(phoneNumber)){
                    layer.msg('请输入正确的手机号码', {icon: 2});
                    return;
                }
                
                // 构建短信模板参数
                var templateParams = {
                    product: productNames,
                    count: items.length,
                    store: items[0].storenum
                };
                
                // 显示加载状态
                var loadIndex = layer.load(1, {shade: [0.3, '#000']});
                
                // 发送短信请求
                admin.req({
                    url: baseUrl + 'storealert/send-alert',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        phoneNumbers: phoneNumber,
                        templateParams: templateParams
                    }),
                    success: function(res){
                        layer.close(loadIndex);
                        if(res.code === 200){
                            layer.msg('短信发送成功', {icon: 1});
                        } else {
                            layer.msg('短信发送失败：' + res.msg, {icon: 2});
                        }
                        layer.close(index);
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求异常：' + error, {icon: 2});
                        layer.close(index);
                    }
                });
            });
        }
    });

    // 关闭弹框
    function closeLayer() {
        layer.closeAll();
    }

    // 确保所有输入参数都是ASCII字符
    const generateSignature = (params) => {
        // 移除所有非ASCII字符
        const cleanParams = Object.entries(params).reduce((acc, [key, value]) => {
            acc[key] = String(value).replace(/[^\x00-\x7F]/g, '');
            return acc;
        }, {});
        
        // 生成签名
        return calculateSignature(cleanParams);
    }

</script>

<style>
    .layui-col-md3,
    .layui-col-md6,
    #reset-btn,
    #search-btn {
        margin-top: 10px;
    }
    
    /* 高亮显示低库存行 */
    .low-stock {
        background-color: #fff2f0;
    }
    
    /* 美化按钮图标 */
    .layui-btn .layui-icon {
        margin-right: 5px;
    }
    
    /* 增加弹出层样式 */
    .custom-layer .layui-layer-title {
        background-color: #1E9FFF;
        color: #fff;
    }
    
    /* 长文本省略显示 */
    .ellipsis {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>